package com.hupu.jrs.ui.thread

import android.app.Activity
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.GridLayout
import android.widget.TextView
import javax.inject.Inject
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.hupu.jrs.R
import com.hupu.jrs.ui.content.ContentActivity
import com.hupu.jrs.util.ResourceUtil
import com.hupu.jrs.util.SettingPrefUtil
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.functions.Func1
import rx.schedulers.Schedulers

/**
 * Created by sll on 2016/3/9.
 */
class ThreadListAdapter @Inject
constructor(private val mActivity: Activity, private val mReadThreadDao: ReadThreadDao) : RecyclerView.Adapter<ThreadListAdapter.ViewHolder>() {

    private var threads: List<Thread>? = null

    private var mLastPosition = -1

    init {
        threads = emptyList()
    }

    fun bind(threads: List<Thread>) {
        this.threads = threads
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_list_thread, parent, false)
        return ViewHolder(v)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val thread = threads!![position]
        holder.thread = thread
        holder.tvTitle!!.setTextSize(TypedValue.COMPLEX_UNIT_PX, SettingPrefUtil.getTitleSize(mActivity))
        holder.tvTitle!!.text = Html.fromHtml(thread.getTitle())
        if (thread.getLightReply() != null && thread.getLightReply() > 0) {
            holder.tvLight!!.setText(String.valueOf(thread.getLightReply()))
            holder.tvLight!!.visibility = View.VISIBLE
        } else {
            holder.tvLight!!.visibility = View.GONE
        }
        holder.tvReply!!.setText(thread.getReplies())

        holder.tvSingleTime!!.visibility = View.VISIBLE
        holder.tvSummary!!.visibility = View.GONE
        holder.grid!!.visibility = View.GONE
        if (thread.getForum() != null) {
            holder.tvSingleTime!!.setText(thread.getForum().getName())
        } else {
            holder.tvSingleTime!!.setText(thread.getTime())
        }
        Observable.just(thread.getTid())
                .map(Func1<String, Boolean> { s -> mReadThreadDao.queryBuilder().where(ReadThreadDao.Properties.Tid.eq(s)).count() > 0 })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1<Boolean> { aBoolean ->
                    if (aBoolean!!) {
                        holder.tvTitle!!.setTextColor(
                                ResourceUtil.getThemeAttrColor(mActivity, android.R.attr.textColorSecondary))
                    } else {
                        holder.tvTitle!!.setTextColor(
                                ResourceUtil.getThemeAttrColor(mActivity, android.R.attr.textColorPrimary))
                    }
                })
        showItemAnim(holder.cardView, position)
    }

    fun showItemAnim(view: View?, position: Int) {
        if (position > mLastPosition) {
            val animation = AnimationUtils.loadAnimation(view!!.context, R.anim.item_bottom_in)
            animation.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation) {
                    view.alpha = 1f
                }

                override fun onAnimationEnd(animation: Animation) {}

                override fun onAnimationRepeat(animation: Animation) {}
            })
            view.startAnimation(animation)
            mLastPosition = position
        }
    }

    //    protected void buildMultiPic(final GroupThread thread, final GridLayout gridLayout) {
    //        if (mSettingPrefHelper.getLoadPic()) {
    //            gridLayout.setVisibility(View.VISIBLE);
    //            final int count = thread.getCover().size();
    //            final List<String> pics = new ArrayList<String>();
    //            for (int i = 0; i < count; i++) {
    //                SimpleDraweeView imageView = (SimpleDraweeView) gridLayout.getChildAt(i);
    //                imageView.setVisibility(View.VISIBLE);
    //                final Cover threadPic = thread.getCover().get(i);
    //                pics.add(threadPic.getUrl());
    //                imageView.setImageURI(Uri.parse(mSettingPrefHelper.getLoadOriginPic() ? threadPic.getUrl() : threadPic.getUrlSmall()));
    //                imageView.setOnClickListener(new OnClickListener() {
    //                    @Override
    //                    public void onClick(View v) {
    //                        ImagePreviewActivity_.intent(mActivity).extraPic(threadPic.getUrl()).extraPics(pics).start();
    //                    }
    //                });
    //            }
    //
    //            if (count < 9) {
    //                for (int i = 8; i > count - 1; i--) {
    //                    SimpleDraweeView pic = (SimpleDraweeView) gridLayout.getChildAt(i);
    //                    pic.setVisibility(View.GONE);
    //                }
    //            }
    //        } else {
    //            gridLayout.setVisibility(GONE);
    //        }
    //    }

    override fun getItemCount(): Int {
        return threads!!.size
    }

    internal inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        @BindView(R.id.tvTitle)
        var tvTitle: TextView? = null
        @BindView(R.id.tvSummary)
        var tvSummary: TextView? = null
        @BindView(R.id.grid)
        var grid: GridLayout? = null
        @BindView(R.id.tvSingleTime)
        var tvSingleTime: TextView? = null
        @BindView(R.id.tvReply)
        var tvReply: TextView? = null
        @BindView(R.id.tvLight)
        var tvLight: TextView? = null
        @BindView(R.id.cardView)
        var cardView: CardView? = null

        var thread: Thread? = null

        @OnClick(R.id.llThreadItem)
        fun llThreadItemClick() {
            Observable.just(thread!!.getTid())
                    .doOnNext(Action1<String> { s ->
                        mReadThreadDao.queryBuilder()
                                .where(ReadThreadDao.Properties.Tid.eq(s))
                                .buildDelete()
                                .executeDeleteWithoutDetachingEntities()
                        val readThread = ReadThread(null, s)
                        mReadThreadDao.insert(readThread)
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(Action1<String> {
                        notifyDataSetChanged()
                        ContentActivity.startActivity(mActivity, thread!!.getFid(), thread!!.getTid(), "", 1)
                    })
        }

        init {
            ButterKnife.bind(this, view)
        }
    }
}
